package com.woniuxy.service.impl;

import com.woniuxy.entity.Activity;
import com.woniuxy.entity.ActivityExample;
import com.woniuxy.entity.ActivityOrder;
import com.woniuxy.entity.User;
import com.woniuxy.exception.NotNumberException;
import com.woniuxy.mapper.*;
import com.woniuxy.service.ActitvityService;
import com.woniuxy.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;


import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class ActitvityServiceImpl implements ActitvityService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private CampMapper campMapper;

    @Autowired
    private ActivityTypeMapper activityTypeMapper;

    @Override
    public List<Map<String, Object>> selectActivityType() throws Exception {

        return activityTypeMapper.selectActivityType();
    }

    @Override
    public List<Map<String, Object>> selectCampByCity(String city) throws Exception {

        return campMapper.selectCampByCity(city);
    }

    @Override
    public ArrayList<Map<String, Object>> selectActivtyList(String city) throws Exception {
        ArrayList<Map<String, Object>> maps = activityMapper.selectActivtyList(city);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh : mm");
        for (Map<String, Object> map : maps) {
           Date date = (Date) map.remove("time");
            String format = sdf.format(date);
            map.put("time",format);
        }
        return maps;
    }

    @Override
    public List<Map<String ,Object>> selectActivityById(Integer actId) throws Exception {


        return activityMapper.selectActivityById(actId);
    }

    @Autowired
    private ActivityOrderMapper activityOrderMapper;
    @Override
    public Integer saveActiveOrder(ActivityOrder order) throws Exception {
        Integer orderNumber = order.getNumber();
        Integer actId = order.getActId();
        Activity activity = activityMapper.selectByPrimaryKey(actId);
        Integer number = activity.getNumber();
        if(number < orderNumber){
            throw new NotNumberException("活动库存不足");
        }


        order.setTotal(order.getPrice()*order.getNumber());
        order.setOrderTime(new Date());
        order.setStatus(2);
        activityOrderMapper.insertSelective(order);

        String key = "activeOrder#"+order.getActivityOrderId();
        ValueOperations forValue = redisTemplate.opsForValue();
        forValue.set(key,"123", 900, TimeUnit.SECONDS);


//        activity.setNumber(number-orderNumber);
//        activityMapper.updateByPrimaryKeySelective(activity);

        return order.getActivityOrderId();
    }

    @Override
    public int selectCountByStatusAndUserId(Integer status, Integer userId) throws Exception {

        HashMap<String, Object> map = new HashMap<>();
        map.put("status",status);
        map.put("userId" ,userId);
        long count=activityOrderMapper.selectCountByStatusAndUserId(map);

        return (int) count;
    }

    @Override
    public List<Map<String, Object>> selectByStatusAndUserId(Page page, Integer index, Integer userId) throws Exception {
        int number = page.getNumber();
        int pageIndex = page.getPageIndex();
        HashMap<String, Object> map = new HashMap<>();
        map.put("start",(pageIndex-1)*number);
        map.put("number",number);
        map.put("status",index);
        map.put("userId" ,userId);

        List<Map<String, Object>> list = activityOrderMapper.selectOrderLimit(map);
        for (Map<String,Object> orderMap : list) {
            int status = (int)orderMap.get("status");
            if(status == 2){
                Long seconds = redisTemplate.opsForValue().getOperations().getExpire("activeOrder#"+orderMap.get("activityOrderId"));//此方法返回单位为秒过期时长
               if (seconds > 0){
                   int ss = (int)(seconds % 60);
                   int mm = (int) (seconds / 60);
                   orderMap.put("restTime",mm+":"+ss);
               }
            }
        }
        return list;
    }

    @Override
    public void updateOrderStatusById(Integer id) throws Exception {
        ActivityOrder order = new ActivityOrder();
        order.setStatus(5);
        order.setActivityOrderId(id);
        activityOrderMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    public void deleteOrderById(Integer id) throws Exception {
        activityOrderMapper.deleteByPrimaryKey(id);
    }

    @Autowired
    private UserMapper userMapper;
    @Override
    public void updateActiveById(User user, Integer number, Integer id, Integer actId) throws Exception {
        ActivityOrder activityOrder = new ActivityOrder();
        activityOrder.setActivityOrderId(id);
        activityOrder.setStatus(3);
        activityOrderMapper.updateByPrimaryKeySelective(activityOrder);

        redisTemplate.delete("activeOrder#"+id);

        Activity activity = activityMapper.selectByPrimaryKey(actId);

        Integer number1 = activity.getNumber();
        ActivityExample activityExample = new ActivityExample();
        ActivityExample.Criteria criteria = activityExample.createCriteria();
        criteria.andActIdEqualTo(actId).andNumberEqualTo(number1);
        activity.setNumber(number1-number);
        activityMapper.updateByExampleSelective(activity,activityExample);

        if(!user.getUserId().equals(0))
             userMapper.updateByPrimaryKeySelective(user);

    }
}
